package com.hyc.MySpring;

import com.hyc.MySpring.Annotation.Autowired;
import com.hyc.MySpring.Annotation.Component;
import com.hyc.MySpring.Annotation.Qualifer;
import com.hyc.MySpring.Annotation.Value;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @projectName: SpringIOC
 * @package: com.hyc.MySpring
 * @className: MyAnnotationConfigApplicationContext
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/24 18:53
 * @version: 1.0
 */
public class MyAnnotationConfigApplicationContext {

    private Map<String, Object> ioc = new HashMap<>();

    public MyAnnotationConfigApplicationContext(String pack) {
        //扫描包中的目标类
        Set<BeanDefinition> beanDefinitions = findBeanDefinitions(pack);
        //根据原材料 创建bean
        createObject(beanDefinitions);
        //    自动装载
        autowireObject(beanDefinitions);
    }

    public void autowireObject(Set<BeanDefinition> beanDefinitions) {
        Iterator<BeanDefinition> iterator = beanDefinitions.iterator();
        while (iterator.hasNext()) {
            BeanDefinition beanDefinition = iterator.next();
            Class clazz = beanDefinition.getBeanClass();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                Autowired annotation = field.getAnnotation(Autowired.class);
                if (annotation != null) {
                    Qualifer qualifer = field.getAnnotation(Qualifer.class);
                    if (qualifer != null) {
                        try {
                            //byName
                            String beanName = qualifer.value();
                            Object bean = getBean(beanName);
                            String fieldName = field.getName();
                            String mothedName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                            Method method = clazz.getMethod(mothedName, field.getType());
                            Object object = getBean(beanDefinition.getBeanName());
                            System.out.println(bean);
                            method.invoke(object, bean);
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    } else {
                        //byType
                    }
                }
            }
        }
    }

    public Object getBean(String beanName) {
        return ioc.get(beanName);
    }

    public void createObject(Set<BeanDefinition> beanDefinitions) {
        Iterator<BeanDefinition> iterator = beanDefinitions.iterator();
        while (iterator.hasNext()) {
            BeanDefinition beanDefinition = iterator.next();
            Class clazz = beanDefinition.getBeanClass();
            String beanName = beanDefinition.getBeanName();
            try {
                //创造对象
                Object objects = clazz.getConstructor().newInstance();
                //完成属性的赋值
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    Value valueAnnotation = declaredField.getAnnotation(Value.class);
                    if (valueAnnotation != null) {
                        String value = valueAnnotation.value();
                        String fieldName = declaredField.getName();
                        String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                        Method method = clazz.getMethod(methodName, declaredField.getType());
                        //数据类型转换
                        Object val = null;
                        //可能会有很多类型 篇幅过长
                        switch (declaredField.getType().getName()) {
                            case "java.lang.Integer":
                                val = Integer.parseInt(value);
                                break;
                            case "java.lang.String":
                                val = value;
                                break;
                            case "java.lang.Float":
                                val = Float.parseFloat(value);
                                break;
                        }
                        method.invoke(objects, val);
                    }
                }
                ioc.put(beanName, objects);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

        }
    }

    public Set<BeanDefinition> findBeanDefinitions(String pack) {
        //    1 获取包下的所有类
        Set<Class<?>> classes = MyTools.getClasses(pack);
        Iterator<Class<?>> iterator = classes.iterator();
        Set<BeanDefinition> BeanDefinitions = new HashSet<>();
        while (iterator.hasNext()) {
            //    2，遍历这些类 找到添加了注解的类
            Class<?> clazz = iterator.next();
            Component annotation = clazz.getAnnotation(Component.class);
            if (annotation != null) {
                //    获取Compoent的值
                String beanName = annotation.value();
                if ("".equals(beanName)) {
                    //   获取类名首字母小写、
                    String className = clazz.getSimpleName();
                    beanName = className.substring(0, 1).toLowerCase() + className.substring(1, className.length());
                }
                BeanDefinition beanDefinition = new BeanDefinition(beanName, clazz);
                BeanDefinitions.add(beanDefinition);
            }
        }
        //    3. 将这些类封装成BeanDefinition 装载到集合中
        return BeanDefinitions;
    }
}
